import dayjs from 'dayjs'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  if (date.getFullYear() <= 2000) {
    return ''
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}
/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

export function _getQuery(obj) {
  const query = {}
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key] !== '') {
        query[key] = obj[key]
      }
    }
  }
  return query
}

/**
 * @param {Object} obj
 * @return {String}
 */
export function obj2Params(obj) {
  const str = []
  for (const p in obj) {
    str.push(
      encodeURIComponent(p) +
      '=' +
      encodeURIComponent(typeof obj[p] === 'object' ? JSON.stringify(obj[p]) : obj[p])
    )
  }
  return str.join('&')
}

/**
 * @param arr 枚举数组
 * @param key 枚举中作对比的字段名称（一般为唯一值）
 * @param rowValue 单元格数值
 * @param dataName 匹配枚举中的返回字段名称
 * @returns {string}
 */
export function formatColumnMap(arr, key, rowValue, dataName) {
  if (!arr || arr.length === 0) return ''
  let formatValue = ''
  if (arr.length > 0) {
    const match = arr.find(item => item[key] === rowValue)
    if (match) formatValue = match[dataName]
  }
  return formatValue
}
const list = {
  mobile: '^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9]|19[0-9])[0-9]{8}$',
  wildmobile: '^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9]|19[0-9])[0-9]{8}-[0-9]{1,2}$',
  tel: '^(\\d{3,4}-?)?\\d{6,8}$',
  wildtel: '^(\\d{3,4}-?)?\\d{6,8}-[0-9]{1,2}$',
  num: '^\\d*$',
  sfzh: /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
}
export function isWildPhone(d) {
  return isMobile(d) || isTel(d) || isWildMobile(d) || isWildTel(d)
}

export function isPhone(d) {
  return isMobile(d) || isTel(d)
}

function isMobile(d) {
  return isMatch(list.mobile, d)
}

function isMatch(r, s) { return new RegExp(r).test(s) }
function isTel(d) {
  return isMatch(list.tel, d)
}
function isWildMobile(d) {
  return isMatch(list.wildmobile, d)
}
function isWildTel(d) {
  return isMatch(list.wildtel, d)
}

export function isSfzh(d) {
  return isMatch(list.sfzh, d)
}

/**
 *  防抖 debounce
 * @param {Function} func
 * @param {Number} wait
 * @param {Boolean} immediate
 * @returns {Function}
 */

export function debounce(func, wait = '300', immediate = 'true') {
  let timer
  const debounced = function() {
    const context = this
    clearTimeout(timer)
    if (immediate) {
      const callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, wait)
      if (callNow) func.apply(context, arguments)
    } else {
      timer = setTimeout(() => {
        func.apply(context, arguments)
      }, wait)
    }
  }
  return debounced
}

/**
 *  节流 throttle
 * @param {Function} func
 * @param {Number} wait
 * @returns {Function}
 */
export function throttle(func, wait = 200) {
  let timeout = true
  return function() {
    const context = this
    if (!timeout) {
      return
    }
    timeout = false
    setTimeout(() => {
      func.apply(context, arguments)
      timeout = true
    }, wait)
  }
}

export function formatFixed2(value) {
  return isNaN(Number(value)) ? '' : Number(value).toFixed(2)
}

// 字符串首尾去空格
export function trim(str) {
  let temp = str.replace(/^\s+/, '')
  for (var i = temp.length - 1; i >= 0; i--) {
    if (/\s/.test(temp.charAt(i))) {
      temp = temp.substring(0, i + 1)
      break
    }
  }
  return temp
}

// 获取窗口缩放比例
export function obtainZoom() {
  let ratio = 0
  const screen = window.screen
  const ua = navigator.userAgent.toLowerCase()
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio
  } else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI
    }
  } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
    ratio = window.outerWidth / window.innerWidth
  }
  if (ratio) {
    ratio = Math.round(ratio * 100)
  }
  return ratio
  // document.body.style.zoom = 100/Number(m);
}
/**
 * 把设备数组挂到机构下面去
 * @param {机构数组} orgList
 * @param {设备数组} deveceList
 * @returns
 */
export function setDeviceChildren(orgList, deveceList) {
  const arr = JSON.parse(JSON.stringify(orgList))
  arr.forEach(item => {
    const brr = []
    deveceList.forEach(it => {
      if (item.id === it.orgId) {
        it.label = it.deviceName
        it.allName = it.corpName + '————' + it.deviceName
        brr.push(it)
      }
      brr.length ? item.children = brr : ''
    })
  })
  return arr
}
// 根据原始数据计算中心坐标和缩放级别，并为地图设置中心坐标和缩放级别。
export function setZoom(map, points, type) {
  if (points.length > 0) {
    var maxLng = points[0].lng
    var minLng = points[0].lng
    var maxLat = points[0].lat
    var minLat = points[0].lat
    var res
    for (var i = points.length - 1; i >= 0; i--) {
      res = points[i]
      if (res.lng > maxLng) maxLng = res.lng
      if (res.lng < minLng) minLng = res.lng
      if (res.lat > maxLat) maxLat = res.lat
      if (res.lat < minLat) minLat = res.lat
    }
    var cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2
    var cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2
    var zoom = getZoom(map, maxLng, minLng, maxLat, minLat)
    // eslint-disable-next-line no-undef
    map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom)
    if (type) {
      map.setZoom(zoom)
      // eslint-disable-next-line no-undef
      map.panTo(new BMap.Point(cenLng, cenLat))
    }
    // map.centerAndZoom(new BMap.Point(cenLng,cenLat), zoom);
  } else {
    // 没有坐标，显示全中国
    map.centerAndZoom('北京', 12)
  }
}
// 根据经纬极值计算绽放级别。
function getZoom(map, maxLng, minLng, maxLat, minLat) {
  var zoom = ['50', '100', '200', '500', '1000', '2000', '5000', '10000', '20000', '25000', '50000', '100000', '200000', '500000', '1000000', '2000000']// 级别18到3。
  // eslint-disable-next-line no-undef
  var pointA = new BMap.Point(maxLng, maxLat) // 创建点坐标A
  // eslint-disable-next-line no-undef
  var pointB = new BMap.Point(minLng, minLat) // 创建点坐标B
  var distance = map.getDistance(pointA, pointB).toFixed(1) // 获取两点距离,保留小数点后两位
  for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
    if (zoom[i] - distance > 0) {
      return 18 - i + 3// 之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
    }
  }
}

/**
 * @param {string} start
 * @param {string} end
 * @returns {string}
 */
export function diffTime(start, end) {
  const f = dayjs(start)
  const l = dayjs(end)
  const second = l.diff(f, 'second')
  console.log(second)
  if (second <= 60) {
    return second + '秒'
  } else {
    const minute = l.diff(f, 'minute')
    if (minute <= 60) {
      return minute + '分钟'
    } else {
      const hour = l.diff(f, 'minute')
      if (hour <= 60) {
        return hour + '小时'
      } else {
        const month = l.diff(f, 'month')
        if (month < 1) {
          const day = l.diff(f, 'day')
          return day + '天'
        }
        if (month <= 12) {
          return month + '月'
        } else {
          const year = l.diff(f, 'year')
          return year + '年'
        }
      }
    }
  }
}
/**
 * @param {string} temp
 * @returns {string}
 */
// 小写数字转大写
export function toChinesNum(temp) {
  const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const unit = ['', '十', '百', '千', '万']
  const strArr = temp.toString().split('').reverse()
  let newNum = ''
  if (temp < 100) {
    strArr.forEach((item, index) => {
      strArr[index] = parseInt(item)
    })
    for (let i = 0; i < strArr.length; i++) {
      newNum = (i === 0 && strArr[i] === 0 && strArr.length < 3 ? '' : (i > 0 && strArr[i] === 0 && strArr[i - 1] === 0 ? '' : (strArr[i] === 1 && strArr[i - 1] <= 9 && strArr[i - 1] !== 0 ? unit[i] + changeNum[strArr[i - 1]] : (strArr[i] === 1 && strArr[i - 1] <= 9 && strArr[i - 1] === 0 && strArr.length < 3 ? unit[i] : changeNum[strArr[i]] + (strArr[i] === 0 ? unit[0] : unit[i]))))) + (strArr[i] === 1 && strArr[i - 1] <= 9 ? '' : newNum)
    }
    return newNum
  } else {
    for (let i = 0; i < strArr.length; i++) {
      newNum = (i === 0 && strArr[i] === 0 ? '' : (i > 0 && strArr[i] === 0 && strArr[i - 1] === 0 ? '' : changeNum[strArr[i]] + (strArr[i] === 0 ? unit[0] : unit[i]))) + newNum
    }
    return newNum
  }
}

export function toDecimal(str, p) {
  if (/^(-?\d+)(\.\d+)?$/.test(str)) {
    return parseFloat(str).toFixed(p || 2) * 1
  }
  return 0
}

// 数字大写
export function convertCurrency(money) {
  // 汉字的数字
  var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  // 基本单位
  var cnIntRadice = ['', '拾', '佰', '仟']
  // 对应整数部分扩展单位
  var cnIntUnits = ['', '万', '亿', '兆']
  // 对应小数部分单位
  var cnDecUnits = ['角', '分', '毫', '厘']
  // 整数金额时后面跟的字符
  var cnInteger = '整'
  // 整型完以后的单位
  var cnIntLast = '元'
  // 最大处理的数字
  var maxNum = 999999999999999.9999
  // 金额整数部分
  var integerNum
  // 金额小数部分
  var decimalNum
  // 输出的中文金额字符串
  var chineseStr = ''
  // 分离金额后用的数组，预定义
  var parts
  // 传入的参数为空情况
  if (money === '') {
    return ''
  }
  money = parseFloat(money)
  if (money >= maxNum) {
    return ''
  }
  // 传入的参数为0情况
  if (money === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转为字符串
  money = money.toString()
  // indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
  if (money.indexOf('.') === -1) {
    integerNum = money
    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 转换整数部分
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0
    const IntLen = integerNum.length
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1)
      const p = IntLen - i - 1
      const q = p / 4
      const m = p % 4
      if (n === '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        zeroCount = 0
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    // 最后+ 元
    chineseStr += cnIntLast
  }
  // 转换小数部分
  if (decimalNum !== '') {
    const decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1)
      if (n !== '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr === '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum === '') {
    chineseStr += cnInteger
  }

  return chineseStr
}

// 金额取分
/**
 * str 金额；p 精度
 * */
export function amountHandle(str, p = 0) {
  const n = Number(str)
  if (!isNaN(n) && typeof n === 'number') {
    const r = Number((n * 100).toFixed(p))
    return r
  }
}

// 秒数转时分秒字符串
export function secondsToHMS(s) {
  const hours = Math.floor(s / 3600)
  const minutes = Math.floor((s % 3600) / 60)
  const remainingSeconds = s % 60
  return `${(hours && hours !== '0') ? hours + '小时' : ''}${(minutes && minutes !== '0') ? minutes + '分钟' : ''}${(remainingSeconds && remainingSeconds !== '0') ? remainingSeconds + '秒' : ''}`
}
